<template>
  <el-select v-model="value"
             :loading="loading"
             :placeholder="placeholder"
             :remote-method="handleRemoteMethod"
             clearable
             filterable
             remote
             reserve-keyword
             @change="handleValueChange"
             @clear="options = []">
    <el-option v-for="item in options" :key="item.bankCode" :label="item.branchName" :value="item.branchName"/>
  </el-select>
</template>

<script lang="ts" setup>

import { computed, ref } from 'vue';
import request from '@/utils/axios/axios-service.ts'

defineOptions({name: 'bank-branch-search'});

const props = defineProps({
  modelValue: {
    type: String,
  },
  placeholder: {
    type: String,
    default: '请输入关键词'
  },
  readonly: {
    type: Boolean,
    default: false
  },
  limit: {
    type: Number,
    default: 30
  },
  regionCode: {
    type: Number,
  },
});

const emit = defineEmits(['update:modelValue', 'change']);
const value = computed({
  get: () => props.modelValue,
  set: (val) => {

  },
});

export type BankBranchData = {
  code: string; // 支行代码
  name: string; // 支行名称
  unionpay_code: string; // 银联代码 = 3位银行代码 + 4位城市代码 + 4位银行编号 + 1位校验
  bank_code: string; // 银行代码
  bank_name: string; // 银行名称
  province_code: number; // 省编码
  city_code: number; // 市编码
  county_code: number; // 区县编码
}

// 远程数据
const options = ref<BankBranchData[]>([]);
const loading = ref(false);
/** 处理远程搜索 */
const handleRemoteMethod = (query: string) => {
  if (query !== '') {
    loading.value = true;
    // 调用接口进行搜索
    request.get('/v1/bank', {params: {name: query, region_code: props.regionCode, action:'branch'}}).then((res: any) => {
      options.value = res.body || [];
      if (options.value.length == 1) {
        let item = options.value[0];
        emit('update:modelValue', item.branchName);
        emit('change', item);
      }
    }).finally(() => loading.value = false);
  } else {
    //options.value = []
  }
};

/** 对外提供方法 */
defineExpose({handleRemoteMethod});

/** 处理值变更事件 */
const handleValueChange = (val: any) => {
  emit('update:modelValue', val);
  if (val && val !== '') {
    let itemList = options.value.filter(item => item.name === val);
    emit('change', itemList.length > 0 ? itemList[0] : null);
  } else {
    emit('change', null);
  }
};

</script>

<style lang="scss" scoped>

</style>
